package com.二叉树.动态二叉树;

import java.util.Deque;
import java.util.LinkedList;


public class TreeNode {
    //左节点
    private TreeNode leftTreeNode;
    //右节点
    private TreeNode rightNode;
    //数据
    private int value;

    public TreeNode getLeftTreeNode() {
        return leftTreeNode;
    }

    public void setLeftTreeNode(TreeNode leftTreeNode) {
        this.leftTreeNode = leftTreeNode;
    }

    public TreeNode getRightNode() {
        return rightNode;
    }

    public void setRightNode(TreeNode rightNode) {
        this.rightNode = rightNode;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public  TreeNode (int value ){
        this.value = value;
    }
    public static TreeNode constructTree(Integer[] num){
        if(num.length == 0 ){
            return new TreeNode(0);
        }
        Deque<TreeNode> nodeDeque = new LinkedList<>();
        //创建一个根结点
        TreeNode root = new TreeNode(num[0]);
        nodeDeque.offer(root);
        TreeNode cur;
        //记录当前行节点的数量(注意不一定是2 的幂，而是上一行中非空节点的数量乘以2)

        int lineNodeNum = 2;
        //记录当前行中数字在数组中的开始位置
        int startIndex = 1 ;
        //记录数组剩余的元素的数量
        int restLength = num.length - 1 ;
        while (restLength > 0 ){
            for (int i  = startIndex;i<startIndex + lineNodeNum;i = i + 2){
                if(i == num.length) {
                    return root;
                }
                cur = nodeDeque.poll();
                if(num[i] != null){
                    cur.leftTreeNode = new TreeNode(num[i]);
                    nodeDeque.offer(cur.leftTreeNode);
                }
                if(i+1 == num.length) {
                    return root;
                }
                if(num[i+1] != null){
                    cur.rightNode = new TreeNode(num[i+1]);
                    nodeDeque.offer(cur.rightNode);
                }
            }
            startIndex += lineNodeNum;
            restLength -= lineNodeNum;
            lineNodeNum = nodeDeque.size() * 2;

        }
        return root;
    }

    @Override
    public String toString() {
        return "   ";
    }

    public static void main(String[] args) {
        Integer[] num = new Integer[]{1,2,3,4,5,6,23,32,43,54,23,234};
        TreeNode root = constructTree(num);
        System.out.println(root);
    }
}
